package com.senmiao.ssm.service.impl;

import com.senmiao.ssm.mapper.AdminMapper;
import com.senmiao.ssm.entity.Admin;
import com.senmiao.ssm.service.AccessControlService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class AccessControlServiceImpl implements AccessControlService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 登录
     * @param username
     * @param password
     */
    @Override
    public void login(String username,String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);
    }

    /**
     * 退出登录
     */
    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            subject.logout();
        }
    }

    @Override
    public Set<String> listPermissionsByUsername(String username) {
        // 拿该用户名对应的所有权限
        Set<String> permissions = adminMapper.listPermissionsByUsername(username);
        // 拿到该用户有的角色
        Set<String> roles = listRolesByUsername(username);
        // 把角色有的权限加进用户的权限列表
        if (roles.size() > 0){
            Set<String> rolesPermission = adminMapper.listPermissionsByRoles(roles);
            if (rolesPermission.size() > 0){
                permissions.addAll(rolesPermission);
            }
        }
        return permissions;
    }

    @Override
    public Set<String> listRolesByUsername(String username) {
        return new HashSet<>(adminMapper.listRolesByUsername(username));
    }


    @Override
    public Admin findPasswordByUsername(String username) {
        return adminMapper.getByUsername(username);
    }

}